package me.firstapp.weixin.controller.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.remoting.RemoteConnectFailureException;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.AbstractJsonObject;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.weixin.member.Member;

@Service
public class BaseController implements HandlerExceptionResolver {
	private static final String SERVICE_EXCEPTION = "_exception";
	private static final String ERROR_PAGE = "common/error";

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception e) {

		e.printStackTrace();
		ModelMap modelMap = new ModelMap();

		if (e instanceof ServiceException) {
			ServiceException serviceException = (ServiceException) e;
			if (request.getRequestURI().endsWith(".do")) {
				AbstractJsonObject abstractJsonObject = new AbstractJsonObject();
				abstractJsonObject.setCode(serviceException.getCode());
				abstractJsonObject.setMsg(serviceException.getStatusObject().getMsg());
				ResponseUtils.renderJson(response, abstractJsonObject);
				return new ModelAndView();
			}
			modelMap.put(SERVICE_EXCEPTION, serviceException);
			return new ModelAndView(ERROR_PAGE, modelMap);
		} else if (e instanceof RemoteConnectFailureException) {
			modelMap.put(SERVICE_EXCEPTION, new ServiceException(StatusHouse.COMMON_STATUS_REQUEST_TIMEOUT));
			return new ModelAndView(ERROR_PAGE, modelMap);
		} else {
			return new ModelAndView(ERROR_PAGE, modelMap);
		}

	}

	/**
	 * 获取登录用户的OpenId
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	protected String getCurrentLoginOpenId(HttpServletRequest request, HttpServletResponse response) {
		String openId = (String) request.getSession().getAttribute("openId");
//		String openId = "otFms0ib9eecFHRe2pa98b-Bfjh0";
		if (StrUtils.isNULL(openId)) {
			System.out
					.println("==========>Cant find openId in session ! Session id is :" + request.getSession().getId());
			throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
		}
		return openId;
	}

	protected String getVipName(int level) {
		String _vipStr = "";
		if (level == Member.VIP_LEVEL_BASE) {
			_vipStr = "会员";
		} else if (level == Member.VIP_LEVEL_HIGHT) {
			_vipStr = "代理";
		} else if (level == Member.VIP_LEVEL_FANS) {
			_vipStr = "粉丝";
		}
		return _vipStr;
	}

}
